package com.lottery.pay.Utils.wxUtil;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.lottery.pay.Constants.WeixinConstant;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WxUtils {

    /**
     * 获取TOKEN
     */
    public static String getToken(String appId, String appSecret) {
        log.info("appId={},appSecret={}",appId,appSecret);
        log.info("Enter getToken()");
        String accessToken = null;
        String tokenPath = WeixinConstant.TOKEN_PATH.replace("APP_ID", appId)
                .replace("APP_SECRET", appSecret);
        String response = HttpsUtil.getMethod(tokenPath);
        JSONObject jsonObject = JSONObject.parseObject(response);
        // 如果请求成功
        if (jsonObject != null) {
            try {
                accessToken = jsonObject.getString("access_token");
                log.info(
                        "get access_token success,effectiveTime={},token={}",
                        jsonObject.getIntValue("expires_in"),
                        jsonObject.getString("access_token"));
            } catch (JSONException e) {
                // 获取token失败
                log.info("get access_token fail,errorcode:{},errormsg:{}",
                        jsonObject.getIntValue("errcode"),
                        jsonObject.getString("errmsg"));
            }
        }
        return accessToken;
    }

    /**
     * 获取Ticket
     */
    public static String getTicket(String access_token) {
        String ticket = null;
        String ticketPath = WeixinConstant.TICKET_PATH;
        ticketPath = ticketPath.replace("ACCESS_TOKEN", access_token);
        String response = HttpsUtil.getMethod(ticketPath);
        log.info("get ticket result = {}", response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        // 请求成功
        if (jsonObject != null) {
            try {
                ticket = jsonObject.getString("ticket");
            } catch (Exception e) {
                log.info("get ticket fail,errorcode:{},errormsg:{}",
                        jsonObject.getIntValue("errcode"),
                        jsonObject.getString("errmsg"));
            }

        }
        return ticket;
    }

}
